<template>
	<view class="h-screen bg-gray-50 flex flex-col overflow-hidden">

		<view class="card" style="padding: 10rpx">
			<view class="grid grid-cols-2 gap-3">
				<view class="bg-orange-50 rounded-xl p-2 flex items-center">
					<text class="text-orange-400 text-sm">待同步</text>
					<text class="text-3xl font-bold text-orange-500">{{
            pendingCount
          }}</text>
				</view>
				<view class="bg-orange-50 rounded-xl p-2 flex items-center">
					<text class="text-green-400 text-sm">总计</text>
					<text class="text-3xl font-bold text-green-500">{{
            displayRecords.length
          }}</text>
				</view>
			</view>
		</view>

		<view class="flex-1 overflow-hidden flex flex-col min-h-0">
			<!-- 表格容器，使用 flex-1 和 min-h-0 确保正确滚动 -->
			<view class="border border-gray-100 rounded-xl overflow-hidden flex flex-col min-h-0 bg-white">
				<!-- 表头固定 -->
				<view class="grid grid-cols-3 py-3 flex-shrink-0">
					<text class="text-center text-sm text-gray-400">时间</text>
					<text class="text-center text-sm text-gray-400">条码</text>
					<text class="text-center text-sm text-gray-400">状态</text>
				</view>
			</view>

			<view class="flex-1 overflow-y-auto min-h-0" @scroll="handleScroll">
				<view v-for="(record, index) in displayRecords" :key="index" :class="[
            'grid grid-cols-3 py-3 border-b border-gray-50 transition-colors',
            index === 0 ? 'bg-blue-50' : 'hover:bg-gray-50 active:bg-gray-100',
          ]" @click="showRecordDetail(record)">
					<text class="text-center text-sm text-gray-600">
						{{ formatTime(record.timestamp) }}
					</text>
					<text class="text-center text-sm font-mono text-gray-600 truncate px-1">
						{{ record.code }}
					</text>
					<view class="flex justify-center">
						<text :class="[
                'px-2 py-0.5 rounded-full text-xs',
                record.synced
                  ? 'bg-green-50 text-green-500'
                  : 'bg-orange-50 text-orange-500',
              ]">
							{{ record.synced ? "已同步" : "待同步" }}
						</text>
					</view>
				</view>
				<view v-if="loading" class="text-center py-2">
					<text>加载中...</text>
				</view>
			</view>
		</view>

		<view class="bg-white shadow-up-lg px-4 py-3 border-t border-gray-100 flex-shrink-0">
			<button
				class="w-full h-12 bg-gradient-to-r from-primary to-primary-dark text-white rounded-xl text-lg font-medium shadow-lg shadow-primary/20 active:translate-y-0.5 transition-transform flex items-center justify-center space-x-2"
				@click="syncNow">
				<text>立即同步</text>
			</button>
		</view>

		<uni-popup ref="recordDetailPopup" type="center" :mask-click="true">
			<view class="bg-white rounded-2xl w-[680rpx] max-h-[80vh] overflow-hidden relative z-50"
				@touchmove.stop.prevent>
				<view
					class="bg-gradient-to-r from-primary to-primary-dark px-4 py-3 flex justify-between items-center sticky top-0 z-10">
					<text class="text-lg font-medium text-white">记录详情</text>
					<text class="text-xl text-white/80 hover:text-white px-2 cursor-pointer"
						@click="recordDetailPopup.close()">×</text>
				</view>
				<scroll-view scroll-y="true" class="p-4" :style="{ maxHeight: 'calc(80vh - 100rpx)', width: 'auto' }"
					@touchmove.stop>
					<view class="space-y-3">
						<view class="bg-gray-50/80 rounded-lg p-3">
							<view class="flex items-center mb-2">
								<view class="w-1 h-4 bg-primary rounded-full mr-2"></view>
								<text class="text-sm font-medium">基本信息</text>
							</view>
							<view class="space-y-2">
								<view class="flex items-center">
									<text class="w-24 text-gray-500 text-sm">时间：</text>
									<text class="flex-1 text-primary text-lg">{{
                    formatDateTime(currentRecord?.timestamp)
                  }}</text>
								</view>
								<view class="flex items-center">
									<text class="w-20 text-gray-500 text-sm">操作类型：</text>
									<text :class="[
                      'px-2 py-0.5 rounded-full text-lg font-medium',
                      currentRecord?.type === 'in'
                        ? 'bg-green-50 text-green-600'
                        : 'bg-pink-50 text-pink-600',
                    ]">
										{{ currentRecord?.type === "in" ? "入库" : "出库" }}
									</text>
								</view>
								<view class="flex items-center">
									<text class="w-20 text-gray-500 text-sm">同步状态：</text>
									<view class="flex items-center">
										<view :class="[
                        'w-1.5 h-1.5 rounded-full mr-1.5',
                        currentRecord?.synced
                          ? 'bg-green-500'
                          : 'bg-orange-500',
                      ]" />
										<text :class="[
                        'px-2 py-0.5 rounded-full text-lg font-medium',
                        currentRecord?.synced
                          ? 'bg-green-50 text-green-600'
                          : 'bg-orange-50 text-orange-600',
                      ]">
											{{ currentRecord?.synced ? "已同步" : "待同步" }}
										</text>
									</view>
								</view>
							</view>
						</view>

						<view class="bg-gray-50/80 rounded-lg p-3">
							<view class="flex items-center mb-2">
								<view class="w-1 h-4 bg-primary rounded-full mr-2"></view>
								<text class="text-sm font-medium">条码信息</text>
							</view>
							<view class="space-y-2">
								<view class=" font-mono text-base bg-gray-100 px-2 py-0.5 rounded break-all">
									条码：{{ currentRecord?.code }}</view>
								<view class=" font-mono text-base bg-gray-100 px-2 py-0.5 rounded break-all">
									物料名称：{{currentRecord?.productName }}</view>
								<!-- 	<text
										class="flex-1 font-mono text-base bg-gray-100 px-2 py-0.5 rounded break-all">执行标准：{{currentRecord?.specification}}</text> -->
								<view class=" font-mono text-lg bg-gray-100 px-2 py-0.5 rounded break-all">
									生产日期：{{ currentRecord?.productDate}}</view>
								<view class=" font-mono text-lg bg-gray-100 px-2 py-0.5 rounded break-all">
									重量：{{ currentRecord?.weight}}</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		useGetScandata,
		useGetMaterial
	} from "@/hooks/index.js"
	import {
		kingdeeSave
	} from "@/network/apis.ts";
	import {
		msg
	} from "@/utils/msg";
	import {
		getCharCount,
		formatTime,
		formatDateTime,
		changeDataFormat

	} from '@/utils/util.js'
	import {
		StorageService
	} from "@/utils/storage";


	// #ifdef APP-PLUS
	const {
		initListen,
		stopListen
	} = useGetScandata();

	initListen();
	//@ts-ignore
	uni.bus.on("scanCode", (message) => {
		handleScan(message);
	});

	onUnload(() => {
		stopListen();
		//@ts-ignore
		uni.bus.off("scanCode");
	});
	// #endif

	onNavigationBarButtonTap(() => {
		uni.showModal({
			title: "提示",
			content: "确认清空?",
			success: async (res) => {
				if (res.confirm) {

					if (pendingCount.value > 0) return msg('有未同步数据，请同步后清空！')

					await StorageService.deleteOldRecords()
				}
			},
		});
	});

	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.src = "../../static/error.wav";
	// 状态变量
	const operationType = ref("in");
	//待同步数量
	const pendingCount = ref(0);
	//总计数量
	const displayRecords = ref([]);
	// 弹窗相关
	const recordDetailPopup = ref(null);
	const currentRecord = ref(null);

	// 显示记录详情
	const showRecordDetail = async (record) => {
		currentRecord.value = record;
		const {
			valueData
		} = await useGetMaterial(record.code)
		if (valueData.length > 0) {
			currentRecord.value.productName = valueData[0].FName
			currentRecord.value.specification = valueData[0].CPZXBZ
			currentRecord.value.productDate = record.code.split("|")[7].slice(0, 6)
			currentRecord.value.weight = (record.code.split("|")[5] / 100) + 'KG'
		}
		console.log(valueData);

		recordDetailPopup.value.open("center");

	};


	// 处理扫码结果
	const handleScan = async (code) => {

		try {
			if (
				!code ||
				typeof code !== "string" ||
				code.trim() === "" ||
				getCharCount(code, "|") !== 8
			) {
				msg("扫码结果为空或无效");
				innerAudioContext.play();
				uni.vibrateShort();
				return;
			}

			const haveLink = code.indexOf("barcode=");

			const trimmedCode = haveLink == -1 ? code : code.split("barcode=")[1];
			// console.log('trimmedCode', trimmedCode);
			// 检查是否复扫码
			const isDuplicate = displayRecords.value.some(
				(record) => record.code === trimmedCode
			);

			if (isDuplicate) {
				// 播放错误提示音和震动
				innerAudioContext.play();
				uni.vibrateShort();
				uni.showToast({
					title: "该条码已扫描",
					icon: "error",
					duration: 2000,
				});
				return;
			}

			const record = {
				id: Date.now().toString(),
				code: trimmedCode,
				productName: ``,
				specification: "",
				type: operationType.value,
				timestamp: new Date().getTime(),
				synced: 0
			};

			const {
				success,
				record: savedRecord
			} = await StorageService.saveRecord(
				record
			);
			if (success && savedRecord) {
				// getScanHistory();
				displayRecords.value.unshift(record)
				pendingCount.value++
				uni.vibrateShort();
				plus.device.beep(1);
			}
		} catch (error) {
			// 播放错误提示音和震动
			innerAudioContext.play();
			uni.vibrateShort();
			uni.showToast({
				title: error.message || "扫码处理失败",
				icon: "none",
				duration: 3000,
			});
		}
	};

	// 获取统计信息
	const getScanHistory = async () => {
		try {
			// 获取所有记录
			const records = await StorageService.getRecords();

			displayRecords.value = records;
			//获取待同步数据
			pendingCount.value = records.filter(item => !item.synced).length

		} catch (error) {
			console.error("获取统计信息失败:", error);
		}
	};


	// 立即同步
	const syncNow = () => {
		try {
			// 检查网络状态
			uni.getNetworkType({
				complete: async (res) => {
					let networkType = res.networkType || "none";
					if (networkType === "none")
						return msg("当前无网络,请先检查您的网络状态");

					//获取待同步数据
					const pendingRecords = displayRecords.value.filter(item => !item.synced)

					if (pendingRecords.length === 0) {
						uni.showToast({
							title: "没有需要同步的记录",
							icon: "none",
						});
						return;
					}

					uni.showLoading({
						title: "正在同步...",
					});

					const kingdeeData = await updataKingdee(pendingRecords);

					if (!kingdeeData) return;
					// 标记记录为已同步
					const recordIds = pendingRecords.map((record) => record.id);
					const success = await StorageService.markAsSynced(recordIds);

					if (success) {

						// 更新待同步数量
						pendingCount.value = 0;
						getScanHistory();
						uni.showToast({
							title: `已同步${pendingRecords.length}条`,
							icon: "success",
						});
					} else {
						throw new Error("同步失败");
					}
				},
			});
		} catch (error) {
			console.error("同步失败:", error);
			uni.showToast({
				title: "同步失败",
				icon: "none",
			});
		} finally {
			uni.hideLoading();
		}
	};

	// 上传金蝶逻辑
	const updataKingdee = (pendingRecords) => {
		return new Promise(async (resolve, reject) => {


			const FEntity = pendingRecords.map((item) => ({
				FMaterialId: {
					FMaterialId: item.code.split("|")[3],
				},
				FCustId: {
					FCustId: item.code.split("|")[4],
				},
				FBPL_Weight: item.code.split("|")[5] / 100,
				FBPL_Machine: item.code.split("|")[1],
				FBPL_ProduceDate: changeDataFormat(item.code.split("|")[7]),
				FBPL_Datetime: formatTime(item.timestamp),
				FBPL_BarCode: item.code,
			}));

			const {
				data: saveRes
			} = await kingdeeSave({
				formId: "BPL_InStockUpload",
				data: {
					isShowLoading: true,
					IsAutoSubmitAndAudit: true,
					Model: {
						FOrgId: {
							FNumber: uni.ORGNUMBER,
						},
						FEntity,
					},
				},
			});

			if (saveRes.Result.ResponseStatus.IsSuccess == true) {
				resolve(true);
			} else {
				msg(saveRes.Result.ResponseStatus.Errors[0].Message);
				reject(false);
			}

		});
	};

	const initOperationType = () => {
		const pages = getCurrentPages();
		const page = pages[pages.length - 1];
		const type = page.$page?.options?.type;
		if (type === "in" || type === "out") {
			operationType.value = type;
		}
	};

	onMounted(async () => {
		const initPage = async () => {
			initOperationType();
			await getScanHistory();
		};

		if (uni.$dbReady) {
			await initPage();
		} else {
			uni.bus.on("dbReady", async () => {
				await initPage();
			});
		}
	});

	// 在组件卸载时移除事件监听
	onUnmounted(() => {
		uni.bus.off("dbReady");
	});

	const loading = ref(false); // 加载状态

	const handleScroll = async (event) => {
		const {
			scrollTop,
			scrollHeight,
			clientHeight
		} = event.target;
		if (scrollHeight - scrollTop <= clientHeight + 50 && !loading.value) {
			loading.value = true; // 设置加载状态
			await loadMoreRecords(); // 加载更多记录
			loading.value = false; // 重置加载状态
		}
	};

	const loadMoreRecords = async () => {
		// 这里可以实现加载更多的逻辑，比如从数据库中获取更多记录
		// 例如，假设我们每次加载10条记录
		const additionalRecords = await StorageService.getRecords(); // 获取更多记录
		displayRecords.value.push(...additionalRecords); // 将新记录添加到显示列表
	};
</script>